<?php
require(dirname(dirname(__FILE__))."/Config/config.php");
require(dirname(dirname(__FILE__))."/jssdk.php");
require(dirname(dirname(dirname(__FILE__)))."/Qiaqia/Core/WxPay.Exception.php");
require_once dirname(__FILE__).'/log.php';

//初始化日志
// $logHandler= new CLogFileHandler(dirname(dirname(__FILE__))."/logs/debug.log");
// $log = Log::Init($logHandler, 15);


class wxpayController extends appController{
	private $configUlr = "Mobile/Config/pay.json";
	public $wxid = 0;//数据库Id
	
	public $m;//自己的model
	public $info=array();//当前用户的微信信息
	public  function __construct(){
		parent::__construct();
		//基础信息构建
		$this->m = Model('wxpay');
		//微信分享参数构建
		$jsdk = $this->m ->get_jsdk();
	
		$this->assign("signPackage", $jsdk);
	
		//当前用户的微信id
		$this->wxid = $_SESSION['xywxid']?$_SESSION['xywxid']:0;
	
		if($this->wxid>0)
		{
			//当前用户的微信信息
			$this->info = $this->m->get_record($this->wxid);
			$this->assign('info',$this->info);
		}
		
	}
// 	public function index(){
// 		if(!isset($_SESSION['wxid']))
// 		{
// 			//是否已授权
// 			$this->check_member();
// 		}else{
			
// 			$config[c] = array('site_name' => "小王子");
// 			$this->assign_global($config);
			
// 			$this->display('index.html');
// 		}
// 	}
	
	public function set()
	{
		$_SESSION['xywxid']=$_GET['wxid'];
	}
	//需要授权才可进入游戏
	public function canIn()
	{
	    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	    
		if(!$this->info)
		{
		    
			header("Location:".$url);
			exit;
		}
	}
	
	private function get_shop_number(){
		$cfg['card1_total'] = isset($_POST['card1_total'])?intval($_POST['card1_total']):0;
		$cfg['card2_total'] = isset($_POST['card2_total'])?intval($_POST['card2_total']):0;
		$cfg['card3_total'] = isset($_POST['card3_total'])?intval($_POST['card3_total']):0;
		$cfg['card4_total'] = isset($_POST['card4_total'])?intval($_POST['card4_total']):0;
		$cfg['pay_place'] = isset($_POST['pay_place'])?intval($_POST['pay_place']):1;
		$cfg['codes'] = isset($_POST['codes'])?$_POST['codes']:"";
		$cfg['code_money'] = isset($_POST['code_money'])?intval($_POST['code_money']):0;
		$cfg['total'] = intval($cfg['card1_total']+$cfg['card2_total']+$cfg['card3_total']+$cfg['card4_total']*2);
		return $cfg;
	}
	/**
	 * 预下单
	 */
	public function beforehandPay(){
// 		Log::DEBUG("begin pay");
		//$this->canIn();
// 		echo "aaa";
		$path = ROOT_PATH.$this->configUlr;
		$json = json_decode(file_get_contents($path), true);
		$cfg = $this->get_shop_number();
		$result = $this->assembledData($json,$cfg);
		if($result['return_code']!="SUCCESS"||$result['result_code']!="SUCCESS"){
			$resu = array("error"=>1);
			$resu['result'] = $result;
			print_r(json_encode($resu));
		}else{
			$res = array(
					"appId" 	=> $json['appid'],
					"nonceStr"	=> "".$result['nonce_str'],
					"package"	=> "prepay_id=".$result['prepay_id'],
					"signType"	=> "MD5",
					"timeStamp"	=> yf_time()
			);
			ksort($res);
			$string = $this->ToUrlParams($res);
			//签名步骤二：在string后加入KEY
			$string = $string . "&key=".$json['key'];
			//签名步骤三：MD5加密
			$string = md5($string);
			//签名步骤四：所有字符转为大写
			$sign = strtoupper($string);
// 			$stringA = $this->ToUrlParams($res)."&key=".$json['key'];
// 			$sign=strtoupper(md5($stringA));
			$res['paySign'] = $sign;
			$resu = array("error"=>0);
			$resu['result'] = $res;
			$resu['out_trade_no'] = $result['out_trade_no'];
			print_r(json_encode($resu));
		}
	}
	
	public function chooseWXPay(){
		$this->canIn();
		$id = $_GET['wx_pay_id'];
		$result = $this->m->get_wx_pay_by_id($id,$this->info['wxid']);
		if(!$result){
			$resu = array("error"=>1,"content"=>"该单已失效，请重新下单");
			print_r(json_encode($resu));exit();
		}
		if($result['pay_status']=="SUCCESS"){
			$resu = array("error"=>1,"content"=>"该单已付款成功，如显示未付款，请刷新本页面！");
			print_r(json_encode($resu));exit();
		}
		$path = ROOT_PATH.$this->configUlr;
		$json = json_decode(file_get_contents($path), true);
		$nonce_str = hy_rand(16);
		$res = array(
				"appId" 	=> $json['appid'],
				"nonceStr"	=> $nonce_str,
				"package"	=> "prepay_id=".$result['prepay_id'],
				"signType"	=> "MD5",
				"timeStamp"	=> yf_time()
		);
		ksort($res);
		
		$string = $this->ToUrlParams($res);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=".$json['key'];
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$sign = strtoupper($string);
		// 			$stringA = $this->ToUrlParams($res)."&key=".$json['key'];
		// 			$sign=strtoupper(md5($stringA));
		$res['paySign'] = $sign;
		$resu = array("error"=>0);
		$resu['result'] = $res;
		$resu['out_trade_no'] = $result['out_trade_no'];
		print_r(json_encode($resu));
	}
	
	private function assembledData($json,$cfg){
		$nonce_str = hy_rand(32);
		$out_trade_no = $this->m->get_out_trade_no($json['mch_id']);
		$time_start = date("YmdHis");
		$time = time()+120*60;
		$time_expire = date("YmdHis",$time);
		$spbill_create_ip = hy_getIP();
// 		$json['notify_url'] = urlencode($json['notify_url']);
		//计算总费用
		$total = $this->get_total_cost($cfg);
		$signData = array(
				"appid"  			=> $json['appid'],
				"body"				=> "小王子体验馆门票--凭卡券到现场兑换门票",
				"detail"			=> "凭卡券可到小王子中国行活动现场换领入场门票",
				"mch_id" 			=> $json['mch_id'],
				"nonce_str" 		=> $nonce_str,
				"notify_url"		=> $json['notify_url'],
				"openid"			=> $this->info['openid'],
				"out_trade_no"		=> $out_trade_no,
				"spbill_create_ip"	=> $spbill_create_ip,
				"time_expire"		=> $time_expire,
				"time_start"		=> $time_start,
				"total_fee"			=> $total,
				"trade_type"		=> $json['trade_type']
		);
		
		//签名步骤一：按字典序排序参数
		ksort($signData);
		$string = $this->ToUrlParams($signData);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=".$json['key'];
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$sign = strtoupper($string);
		
		
// 		$stringA = $this->ToUrlParams($signData)."&key=".;
// 		echo $stringA;exit;
// 		$sign=strtoupper(md5($stringA));
		$signData['sign'] = $sign;
		
// 		$str = "<xml>
// 				   <appid>$signData[appid]</appid>
// 				   <body>$signData[body]</body>
// 				   <detail>$signData[detail]</detail>
// 				   <mch_id>$signData[mch_id]</mch_id>
// 				   <nonce_str>$signData[nonce_str]</nonce_str>
// 				   <notify_url>$signData[notify_url]</notify_url>
// 				   <openid>$signData[openid]</openid>
// 				   <out_trade_no>$signData[out_trade_no]</out_trade_no>
// 				   <spbill_create_ip>$signData[spbill_create_ip]</spbill_create_ip>
// 				   <time_expire>$signData[time_expire]</time_expire>
// 				   <time_start>$signData[time_start]</time_start>
// 				   <total_fee>$signData[total_fee]</total_fee>
// 				   <trade_type>$signData[trade_type]</trade_type>
// 				   <sign>$signData[sign]</sign>
// 				</xml>";
		$xml = "<xml>";
		foreach ($signData as $key=>$val)
		{
			if (is_numeric($val)){
				$xml.="<".$key.">".$val."</".$key.">";
			}else{
				$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			}
		}
		$xml.="</xml>";
		$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		$result=$this->post_it($url, $xml);
		$result=(array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
		if($result['return_code']=="SUCCESS"&&$result['result_code']=="SUCCESS"){
			$info['wxid'] = $this->wxid;
			$info['time_start'] = $signData['time_start'];
			$info['time_expire'] = $signData['time_expire'];
			$info['total_fee'] = $signData['total_fee'];
			$info['out_trade_no'] = $signData['out_trade_no'];
			$info['prepay_id'] = $result['prepay_id'];
			$info['pay_status'] = "NOTPAY";
			
			$info['card1_total'] = $cfg['card1_total'];
			$info['card2_total'] = $cfg['card2_total'];
			$info['card3_total'] = $cfg['card3_total'];
			
			$info['card1_total'] = $cfg['card1_total']+$cfg['card4_total']*2;
			
			$info['pay_place'] = $cfg['pay_place'];
			$info['total'] = $cfg['total'];
			$info['codes'] = $cfg['codes'];
			$info['code_money'] = $cfg['code_money'];
			
			$hid = $this->m->insert($info,"wx_pay");
			$result['wx_pay_id'] = $hid;
			$result['out_trade_no'] = $out_trade_no;
			
		}else{
			
		}
		return $result;
	}
	
	/**
	 * 用post方法获取数据
	 * @param $url
	 * @param $data
	 * @return
	 */
	public function post_it($url, $data)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($curl);
		if($result){
			curl_close($curl);
			return $result;
		}
		else {
			$error = curl_errno($curl);
			curl_close($curl);
			return false;
		}
	}
	
	public function get_total_cost($cfg){
		$total = 0;
		//a卡
		// 邀请码不与第二张78元重叠  jack
// 		if($cfg['code_money']!=0){
// 			$total = 88*intval($cfg["card1_total"]);
// 			$total = $total-$cfg['code_money']*$cfg['card1_total'];
// 		}else{
// 			$total = intval(78*($cfg['card1_total']-1))+88;
// 		}
		$total = 88*intval($cfg["card1_total"]);
		//b卡
		$total = $total + intval($cfg['card2_total']*68);
		//c卡
		$total = $total + intval($cfg['card3_total']*38);
		
		$total = $total + intval($cfg['card4_total']*100);
		
// 		if($cfg['code_money']!=0){
// 			$total = $total-$cfg['code_money']*$cfg['card1_total'];
// 		}
		if($_SESSION['xywxid']=="24761")
		{
		    return 100;
		}
		//return $total;
		return $total*100;
	}
	
	
	public function get_total(){
		$cfg['card1_total'] = $_GET['card1_total'];
		$cfg['card2_total'] = $_GET['card2_total'];
		$cfg['card3_total'] = $_GET['card3_total'];
		$cfg['card4_total'] = $_GET['card4_total'];
		echo $this->get_total_cost($cfg);
	}
	
	public function ToUrlParams($values){
		$buff = "";
		foreach ($values as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	/**
	 * 此功能主要是再去确认支付订单是否已经支付
	 * 返回值为true，表示已经支付
	 * false，表示未支付
	 */
	public function orderquery(){
		$out_trade_no = $_GET['out_trade_no'];
		$path = ROOT_PATH.$this->configUlr;
		$json = json_decode(file_get_contents($path), true);
		$nonce_str = hy_rand(16);
		$signData = array(
				"appid"  			=> $json['appid'],
				"mch_id" 			=> $json['mch_id'],
				"nonce_str"			=> $nonce_str,
				"out_trade_no" 	=> $out_trade_no,
		);
		ksort($signData);
		$stringA = $this->ToUrlParams($signData)."&key=".$json['key'];
		$sign=strtoupper(md5($stringA));
		$signData['sign'] = $sign;
		$str = "<xml>
				   <appid>$signData[appid]</appid>
				   <mch_id>$signData[mch_id]</mch_id>
				   <nonce_str>$signData[nonce_str]</nonce_str>
				   <out_trade_no>$signData[out_trade_no]</out_trade_no>
				   <sign>$signData[sign]</sign>
				</xml>";
		$url = "https://api.mch.weixin.qq.com/pay/orderquery";
		$result=$this->post_it($url, $str);
		$result=(array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
		if($result['return_code']=="SUCCESS"&&$result['result_code']=="SUCCESS"){
			if($result['trade_state'] =="SUCCESS"){
				//判断是否已经修改，如果是的话，不修改
				if($this->m->is_pay($result['out_trade_no'])){
					echo "SUCCESS";
					exit();
				}else{//不是已经支付的话,修改为支付，跳转至领取卡券页面
					$info['pay_status'] = "SUCCESS";
					$info['transaction_id'] = $result['transaction_id'];
					$id = $this->m->get_id_by_trade($result['out_trade_no']);
					$this->m->update($info,array("table"=>"wx_pay","id"=>$id));
					echo "SUCCESS";exit();
				}
				
			}
			
		}
		echo "FAIL";
	}
	
	
	public function main(){
	    $this->check_member();
		$pay_place = isset($_REQUEST['pay_place'])?intval($_REQUEST['pay_place']):1;
	    if(Model('suipai')->isPaySucess($_SESSION['xywxid'])){
	    	$url = "http://g4.shfyuan.com/xy/index.php?g=mobile&m=picture&a=record";
	    	header('Location:'.$url);
	    }
		$config[c] = array('site_name' => "小王子门票");
		$this->assign_global($config);
		$this->assign("pay_place", $pay_place);
		
		$this->display('stuff_list2.html');
		exit;
		if($pay_place==4){
			$this->display('stuff_list2.html');
		}else{
			$this->display('stuff_list.html');
		}
		
	}
	
	public function main2(){
	    $_SESSION['xywxid']=29720;
	    $this->check_member();
	    $pay_place = isset($_REQUEST['pay_place'])?intval($_REQUEST['pay_place']):1;
	    if(Model('suipai')->isPaySucess($_SESSION['xywxid'])){
	        $url = "http://g4.shfyuan.com/xy/index.php?g=mobile&m=picture&a=record";
	        header('Location:'.$url);
	    }
	    $config[c] = array('site_name' => "小王子门票");
	    $this->assign_global($config);
	    $this->assign("pay_place", $pay_place);
	    if($pay_place==4){
	        $this->display('stuff_list2.html');
	    }else{
	        $this->display('stuff_list.html');
	    }
	
	}
	
	public function saveUser(){
		$this->canIn();
		$res = array("error"=>0,"content"=>"保存信息成功");
		if(!$this->m->is_saved_user($this->wxid)){
			$res['error'] = 2;
			$res['content'] = "用户已填写资料";
			die(json_encode($res));
		}
		$user['phone'] =isset($_REQUEST['phone'])?$_REQUEST['phone']:"";
		if(preg_match("/1[3458]{1}\d{9}$/",$user['phone'])){
		
		}else{
			$res['error'] = 1;
			$res['content'] = "请填写正确的手机号码";
			die(json_encode($res));
		}
		$user['name'] = isset($_REQUEST['name'])?$_REQUEST['name']:$this->info['name'];
		$user['wxid'] = $this->wxid;
		$id = $this->m->insert($user,"wx_pay_user");
		die(json_encode($res));
	}
	
	public function is_saved_user(){
		$this->canIn();
		if(!$this->m->is_saved_user($this->wxid)){
			$res['error'] = 1;
			$res['content'] = "用户已填写资料";
			die(json_encode($res));
		}
		$res['error'] = 0;
		die(json_encode($res));
	}
	
	
	public function push_code_sub_money(){
		$codes = $_GET['codes'];
		$result = $this->m->push_code_sub_money($codes);
		if(!$result){
			$res = array("error"=>1,"content"=>"输入的邀请码有问题，请重新输入");
			die(json_encode($res));
		}else{
			$res['error'] = 0;
			$res['result'] = $result;
			die(json_encode($res));
		}
	}
	
	public function notify(){
		//初始化日志
		$logHandler= new CLogFileHandler(dirname(dirname(__FILE__))."/logs/debug.log");
		$log = Log::Init($logHandler, 15);
		Log::INFO("异步请求开始");
		//获取通知的数据
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		try {
			$path = ROOT_PATH."Mobile/Config/pay.json";
			$json = json_decode(file_get_contents($path), true);
			if(!$xml){
				throw new WxPayException("xml数据异常！");
			}
			libxml_disable_entity_loader(true);
			$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		
			ksort($values);
			$string = $this->ToUrlParams($values);
			//签名步骤二：在string后加入KEY
			$string = $string . "&key=".$json['key'];
			//签名步骤三：MD5加密
			$string = md5($string);
			//签名步骤四：所有字符转为大写
			$result = strtoupper($string);
			if($result != $values['sign']){
				throw new WxPayException("签名错误！");
			}
		
			$m = Model("wxpay");
			//加上逻辑操作
			if($values["return_code"]=="SUCCESS"&&$values["result_code"]=="SUCCESS"){
				Log::INFO("".$values['out_trade_no'].":支付成功");
				$payId = $m->get_wx_pay_by_trade("".$values['out_trade_no']);
				if($payId){
					Log::INFO("订单Id".$payId.":修改支付成功");
					$info['pay_status'] = "SUCCESS";
					$info['transaction_id'] = "".$values['transaction_id'];
					$m->update($info,array("id"=>$payId,"table"=>"wx_pay"));
				}
			}
			$xml = "<xml>
				<return_code><![CDATA[SUCCESS]]></return_code>
				<return_msg><![CDATA[OK]]></return_msg>
				</xml>";
						echo $xml;
			} catch (WxPayException $e){
				Log::ERROR($e->errorMessage());
				Log::ERROR($xml);
				$m= $e->errorMessage();
				$xml = "<xml>
				<return_code><![CDATA[FAIL]]></return_code>
				<return_msg><![CDATA[$m]]></return_msg>
				</xml>";
				echo $xml;
			}
	}
}